package junior.util.wrap;

import java.io.Serializable;
import java.util.Collection;

/**
 * 封装对象和一个分数
 * 
 * @param <T>
 * @author ZhangXiaoye
 * @date 2016年10月6日 上午9:15:50
 */
public class Scored<T> implements Comparable<Scored<?>>, Serializable{

	/** 说明  */
	private static final long serialVersionUID = 1L;

	public final T value;
	
	public Double score;
	
	public Scored(T value, Double score){
		this.value = value;
		this.score = score;
	}

	public T getValue() {
		return value;
	}

	public Double getScore() {
		return score;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((score == null) ? 0 : score.hashCode());
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Scored)) {
			return false;
		}
		@SuppressWarnings("rawtypes")
		Scored other = (Scored) obj;
		if (score == null) {
			if (other.score != null) {
				return false;
			}
		} else if (!score.equals(other.score)) {
			return false;
		}
		if (value == null) {
			if (other.value != null) {
				return false;
			}
		} else if (!value.equals(other.value)) {
			return false;
		}
		return true;
	}

	@Override
	public int compareTo(Scored<?> o) {
		return Double.compare(o.score != null? o.score: Double.NaN, score != null? score: Double.NaN);
	}
	
	public static <T> Scored<T> highestScored(Collection<Scored<T>> list){
		if(list == null || list.isEmpty()){
			return null;
		}
		Scored<T> max = null;
		for(Scored<T> item: list){
			double s = item.score != null? item.score: -Double.MAX_VALUE;
			if(max == null || max.score == null || s > max.score){
				max = item;
			}
		}
		return max;
	}
	
}
